import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'dart:math' as math;
import '../models/sale_model.dart';

// مەھسۇلات مودېلى
class Product {
  final String id;
  final String name;
  final double price;
  final int stock;
  final String unit;
  final String category;

  Product({
    required this.id,
    required this.name,
    required this.price,
    required this.stock,
    required this.unit,
    required this.category,
  });
}

// خېرىدار مودېلى
class Customer {
  final String id;
  final String name;
  final String phone;
  final String address;

  Customer({
    required this.id,
    required this.name,
    required this.phone,
    required this.address,
  });
}

// سودا تۈرى
class SaleItem {
  final String productId;
  final String productName;
  final double price;
  final int quantity;
  final String unit;
  final double total;

  SaleItem({
    required this.productId,
    required this.productName,
    required this.price,
    required this.quantity,
    required this.unit,
    required this.total,
  });
}

// سودا مودېلى
class Sale {
  final String id;
  final String customerName;
  final String customerId;
  final DateTime date;
  final List<SaleItem> items;
  final double total;
  final String paymentMethod;
  final String status;
  final String notes;

  Sale({
    required this.id,
    required this.customerName,
    required this.customerId,
    required this.date,
    required this.items,
    required this.total,
    required this.paymentMethod,
    required this.status,
    this.notes = '',
  });
}

class EditSaleScreen extends StatefulWidget {
  final Sale sale;

  const EditSaleScreen({Key? key, required this.sale}) : super(key: key);

  @override
  State<EditSaleScreen> createState() => _EditSaleScreenState();
}

class _EditSaleScreenState extends State<EditSaleScreen> {
  late TextEditingController _searchController;
  late TextEditingController _discountController;
  late TextEditingController _notesController;
  late String _selectedCustomerId;
  late String _selectedPaymentMethod;
  late String _selectedStatus;
  late List<SaleItem> _cartItems;
  late DateTime _saleDate;

  // ۋاقىتلىق مەھسۇلات سانلىق مەلۇماتلىرى
  final List<Product> _products = List.generate(
    20,
    (index) => Product(
      id: 'P-${(100 + index).toString().padLeft(3, '0')}',
      name: 'مەھسۇلات ${index + 1}',
      price: (10 + math.Random().nextInt(990)).toDouble(),
      stock: math.Random().nextInt(100) + 10,
      unit: _getRandomUnit(),
      category: _getRandomCategory(),
    ),
  );

  // ۋاقىتلىق خېرىدار سانلىق مەلۇماتلىرى
  final List<Customer> _customers = List.generate(
    10,
    (index) => Customer(
      id: 'C-${(100 + index).toString().padLeft(3, '0')}',
      name: 'خېرىدار ${index + 1}',
      phone: '1${(310000000 + math.Random().nextInt(90000000)).toString()}',
      address: 'ئادرېس ${index + 1}',
    ),
  );

  List<Product> _filteredProducts = [];
  double _totalAmount = 0;

  @override
  void initState() {
    super.initState();
    _searchController = TextEditingController();
    _discountController = TextEditingController(text: '0');
    _notesController = TextEditingController(text: widget.sale.notes);
    _selectedCustomerId = widget.sale.customerId;
    _selectedPaymentMethod = widget.sale.paymentMethod;
    _selectedStatus = widget.sale.status;
    _saleDate = widget.sale.date;

    // سودا تۈرلىرىنى سېۋەتكە قوشۇش
    _cartItems = List.from(widget.sale.items);

    _filteredProducts = List.from(_products);
    _calculateTotal();
  }

  // تەسادىپىي بىرلىكنى قايتۇرىدۇ
  static String _getRandomUnit() {
    final units = ['دانە', 'كىلوگرام', 'پاكېت', 'قۇتا', 'مېتىر'];
    return units[math.Random().nextInt(units.length)];
  }

  // تەسادىپىي كاتېگورىيە قايتۇرىدۇ
  static String _getRandomCategory() {
    final categories = [
      'ئېلېكترونلۇق',
      'كىيىم-كېچەك',
      'ئائىلە بۇيۇملىرى',
      'يېمەك-ئىچمەك',
      'باشقا',
    ];
    return categories[math.Random().nextInt(categories.length)];
  }

  // مەھسۇلات ئىزدەش ئىقتىدارى
  void _searchProducts(String query) {
    setState(() {
      if (query.isEmpty) {
        _filteredProducts = List.from(_products);
      } else {
        _filteredProducts = _products
            .where((product) =>
                product.name.toLowerCase().contains(query.toLowerCase()) ||
                product.id.toLowerCase().contains(query.toLowerCase()))
            .toList();
      }
    });
  }

  // سېۋەتكە مەھسۇلات قوشۇش
  void _addToCart(Product product) {
    // سېۋەتتىن كەلگەن مەھسۇلاتنى ئىزدەش
    int existingIndex =
        _cartItems.indexWhere((item) => item.productId == product.id);

    setState(() {
      if (existingIndex >= 0) {
        // مەھسۇلات سېۋەتتە بولسا، سانىنى بىر كۆپەيتىش
        final existingItem = _cartItems[existingIndex];
        final newQuantity = existingItem.quantity + 1;
        _cartItems[existingIndex] = SaleItem(
          productId: existingItem.productId,
          productName: existingItem.productName,
          price: existingItem.price,
          quantity: newQuantity,
          unit: existingItem.unit,
          total: existingItem.price * newQuantity,
        );
      } else {
        // مەھسۇلات سېۋەتتە بولمىسا، يېڭى مەھسۇلات سۈپىتىدە قوشۇش
        _cartItems.add(
          SaleItem(
            productId: product.id,
            productName: product.name,
            price: product.price,
            quantity: 1,
            unit: product.unit,
            total: product.price,
          ),
        );
      }
      _calculateTotal();
    });
  }

  // سېۋەتتىن مەھسۇلات چىقىرىۋېتىش
  void _removeFromCart(int index) {
    setState(() {
      _cartItems.removeAt(index);
      _calculateTotal();
    });
  }

  // مەھسۇلات سانىنى ئۆزگەرتىش
  void _updateQuantity(int index, int newQuantity) {
    if (newQuantity <= 0) {
      _removeFromCart(index);
      return;
    }

    setState(() {
      final item = _cartItems[index];
      _cartItems[index] = SaleItem(
        productId: item.productId,
        productName: item.productName,
        price: item.price,
        quantity: newQuantity,
        unit: item.unit,
        total: item.price * newQuantity,
      );
      _calculateTotal();
    });
  }

  // جەمئىي باھانى ھېسابلاش
  void _calculateTotal() {
    double total = 0;
    for (var item in _cartItems) {
      total += item.total;
    }

    // ئېنىقلاتما بەلگىسىزلىك تەكشۈرۈش
    double discount = 0;
    if (_discountController.text.isNotEmpty) {
      try {
        discount = double.parse(_discountController.text);
      } catch (e) {
        discount = 0;
      }
    }

    setState(() {
      _totalAmount = total * (1 - discount / 100);
    });
  }

  // سودىنى ساقلاش
  void _saveSale() {
    if (_cartItems.isEmpty) {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(
          content: Text('سېۋەت قۇرۇق، مەھسۇلاتلارنى قوشۇڭ'),
          backgroundColor: Colors.red,
        ),
      );
      return;
    }

    if (_selectedCustomerId.isEmpty) {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(
          content: Text('خېرىدار تاللانمىدى'),
          backgroundColor: Colors.red,
        ),
      );
      return;
    }

    // سودىنى يېڭىلاش
    final updatedSale = Sale(
      id: widget.sale.id,
      customerName:
          _customers.firstWhere((c) => c.id == _selectedCustomerId).name,
      customerId: _selectedCustomerId,
      date: _saleDate,
      items: _cartItems,
      total: _totalAmount,
      paymentMethod: _selectedPaymentMethod,
      status: _selectedStatus,
      notes: _notesController.text,
    );

    // ئالدىنقى بەتكە قايتىپ نەتىجىنى قايتۇرۇش
    Navigator.pop(context, updatedSale);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('سودا تەھرىرلەش'),
        actions: [
          IconButton(
            icon: const Icon(Icons.calendar_today),
            onPressed: () async {
              final date = await showDatePicker(
                context: context,
                initialDate: _saleDate,
                firstDate: DateTime(2020),
                lastDate: DateTime.now().add(const Duration(days: 1)),
              );
              if (date != null) {
                setState(() {
                  _saleDate = date;
                });
              }
            },
          ),
        ],
      ),
      body: Column(
        children: [
          // سودا ئۇچۇرلىرى بۆلىكى
          Container(
            padding: const EdgeInsets.all(16),
            color: Colors.blue.shade50,
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  'سودا نومۇرى: ${widget.sale.id}',
                  style: const TextStyle(
                    fontWeight: FontWeight.bold,
                    fontSize: 16,
                  ),
                ),
                const SizedBox(height: 8),
                Text(
                  'سودا چېسلاسى: ${DateFormat('yyyy-MM-dd').format(_saleDate)}',
                  style: const TextStyle(fontSize: 14),
                ),
              ],
            ),
          ),
          Expanded(
            child: Row(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                // مەھسۇلات تاللاش بۆلىكى
                Expanded(
                  flex: 3,
                  child: Card(
                    margin: const EdgeInsets.all(16),
                    child: Padding(
                      padding: const EdgeInsets.all(16),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          TextField(
                            controller: _searchController,
                            decoration: InputDecoration(
                              hintText: 'مەھسۇلات ئىزدەش...',
                              prefixIcon: const Icon(Icons.search),
                              border: OutlineInputBorder(
                                borderRadius: BorderRadius.circular(8),
                              ),
                              contentPadding:
                                  const EdgeInsets.symmetric(vertical: 8),
                            ),
                            onChanged: _searchProducts,
                          ),
                          const SizedBox(height: 16),
                          const Text(
                            'مەھسۇلاتلار',
                            style: TextStyle(
                              fontWeight: FontWeight.bold,
                              fontSize: 16,
                            ),
                          ),
                          const SizedBox(height: 8),
                          Expanded(
                            child: _filteredProducts.isEmpty
                                ? const Center(
                                    child: Text('مەھسۇلات تېپىلمىدى'),
                                  )
                                : ListView.builder(
                                    itemCount: _filteredProducts.length,
                                    itemBuilder: (context, index) {
                                      final product = _filteredProducts[index];
                                      return ListTile(
                                        title: Text(product.name),
                                        subtitle: Text(
                                          '${product.id} | باھاسى: ¥${product.price.toStringAsFixed(2)} | قالدۇق: ${product.stock} ${product.unit}',
                                        ),
                                        trailing: IconButton(
                                          icon: const Icon(
                                              Icons.add_shopping_cart),
                                          onPressed: () => _addToCart(product),
                                        ),
                                      );
                                    },
                                  ),
                          ),
                        ],
                      ),
                    ),
                  ),
                ),
                // سودا تەپسىلاتلىرى بۆلىكى
                Expanded(
                  flex: 5,
                  child: Card(
                    margin: const EdgeInsets.all(16),
                    child: Padding(
                      padding: const EdgeInsets.all(16),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          const Text(
                            'سودا تەپسىلاتلىرى',
                            style: TextStyle(
                              fontWeight: FontWeight.bold,
                              fontSize: 16,
                            ),
                          ),
                          const SizedBox(height: 16),
                          // خېرىدار ۋە تۆلەش ئۇسۇلى تاللاش قاتارى
                          Row(
                            children: [
                              Expanded(
                                child: DropdownButtonFormField<String>(
                                  decoration: const InputDecoration(
                                    labelText: 'خېرىدار',
                                    border: OutlineInputBorder(),
                                  ),
                                  value: _selectedCustomerId,
                                  items: _customers
                                      .map(
                                        (customer) => DropdownMenuItem<String>(
                                          value: customer.id,
                                          child: Text(customer.name),
                                        ),
                                      )
                                      .toList(),
                                  onChanged: (value) {
                                    setState(() {
                                      _selectedCustomerId = value!;
                                    });
                                  },
                                ),
                              ),
                              const SizedBox(width: 16),
                              Expanded(
                                child: DropdownButtonFormField<String>(
                                  decoration: const InputDecoration(
                                    labelText: 'تۆلەش ئۇسۇلى',
                                    border: OutlineInputBorder(),
                                  ),
                                  value: _selectedPaymentMethod,
                                  items: [
                                    'نەق پۇل',
                                    'ئېلېكترونلۇق تۆلەم',
                                    'ئالىپاي',
                                    'ۋېچات تۆلەم',
                                    'باشقا'
                                  ]
                                      .map(
                                        (method) => DropdownMenuItem<String>(
                                          value: method,
                                          child: Text(method),
                                        ),
                                      )
                                      .toList(),
                                  onChanged: (value) {
                                    setState(() {
                                      _selectedPaymentMethod = value!;
                                    });
                                  },
                                ),
                              ),
                              const SizedBox(width: 16),
                              Expanded(
                                child: DropdownButtonFormField<String>(
                                  decoration: const InputDecoration(
                                    labelText: 'ھالەت',
                                    border: OutlineInputBorder(),
                                  ),
                                  value: _selectedStatus,
                                  items: [
                                    'پۈتتى',
                                    'كېچىكتى',
                                    'كۈتۈۋاتىدۇ',
                                    'ئەمەلدىن قالدى'
                                  ]
                                      .map(
                                        (status) => DropdownMenuItem<String>(
                                          value: status,
                                          child: Text(status),
                                        ),
                                      )
                                      .toList(),
                                  onChanged: (value) {
                                    setState(() {
                                      _selectedStatus = value!;
                                    });
                                  },
                                ),
                              ),
                            ],
                          ),
                          const SizedBox(height: 16),
                          // ئېتىبار ۋە ئىزاھات
                          Row(
                            children: [
                              Expanded(
                                child: TextField(
                                  controller: _discountController,
                                  decoration: const InputDecoration(
                                    labelText: 'ئېتىبار (%)',
                                    border: OutlineInputBorder(),
                                  ),
                                  keyboardType: TextInputType.number,
                                  onChanged: (value) {
                                    _calculateTotal();
                                  },
                                ),
                              ),
                              const SizedBox(width: 16),
                              Expanded(
                                flex: 3,
                                child: TextField(
                                  controller: _notesController,
                                  decoration: const InputDecoration(
                                    labelText: 'ئىزاھات',
                                    border: OutlineInputBorder(),
                                  ),
                                ),
                              ),
                            ],
                          ),
                          const SizedBox(height: 16),
                          // سېۋەت تىزىملىكى
                          const Text(
                            'سېۋەت',
                            style: TextStyle(
                              fontWeight: FontWeight.bold,
                              fontSize: 16,
                            ),
                          ),
                          const SizedBox(height: 8),
                          Expanded(
                            child: _cartItems.isEmpty
                                ? const Center(
                                    child: Text('سېۋەت قۇرۇق'),
                                  )
                                : ListView.builder(
                                    itemCount: _cartItems.length,
                                    itemBuilder: (context, index) {
                                      final item = _cartItems[index];
                                      return ListTile(
                                        title: Text(item.productName),
                                        subtitle: Text(
                                          '${item.productId} | باھاسى: ¥${item.price.toStringAsFixed(2)} | جەمئىي: ¥${item.total.toStringAsFixed(2)}',
                                        ),
                                        trailing: Row(
                                          mainAxisSize: MainAxisSize.min,
                                          children: [
                                            IconButton(
                                              icon: const Icon(Icons.remove),
                                              onPressed: () => _updateQuantity(
                                                  index, item.quantity - 1),
                                            ),
                                            SizedBox(
                                              width: 40,
                                              child: Text(
                                                '${item.quantity}',
                                                textAlign: TextAlign.center,
                                              ),
                                            ),
                                            IconButton(
                                              icon: const Icon(Icons.add),
                                              onPressed: () => _updateQuantity(
                                                  index, item.quantity + 1),
                                            ),
                                            IconButton(
                                              icon: const Icon(Icons.delete,
                                                  color: Colors.red),
                                              onPressed: () =>
                                                  _removeFromCart(index),
                                            ),
                                          ],
                                        ),
                                      );
                                    },
                                  ),
                          ),
                          const SizedBox(height: 16),
                          // جەمئىي باھا ۋە ساقلاش كۇنۇپكىسى
                          Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: [
                              Column(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: [
                                  Text(
                                    'مەھسۇلات سانى: ${_cartItems.length}',
                                    style: TextStyle(
                                      color: Colors.grey.shade700,
                                    ),
                                  ),
                                  const SizedBox(height: 4),
                                  Text(
                                    'جەمئىي: ¥${_totalAmount.toStringAsFixed(2)}',
                                    style: const TextStyle(
                                      fontWeight: FontWeight.bold,
                                      fontSize: 20,
                                      color: Colors.blue,
                                    ),
                                  ),
                                ],
                              ),
                              ElevatedButton.icon(
                                icon: const Icon(Icons.save),
                                label: const Text('سودىنى ساقلاش'),
                                style: ElevatedButton.styleFrom(
                                  padding: const EdgeInsets.symmetric(
                                      horizontal: 24, vertical: 12),
                                ),
                                onPressed: _saveSale,
                              ),
                            ],
                          ),
                        ],
                      ),
                    ),
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  @override
  void dispose() {
    _searchController.dispose();
    _discountController.dispose();
    _notesController.dispose();
    super.dispose();
  }
}
